package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
)

func GetUploadPage(c *gin.Context) {

	// 返回html页面，通过gin.H传递模板参数
	c.HTML(http.StatusOK, "upload.html", gin.H{
		"title": "上传页面",
	})
}

func UploadFile(c *gin.Context) {
	log.Println(">>> UploadFile function start  <<<")

	src := "\\file\\"

	gwd, err := os.Getwd()
	fmt.Println(gwd)

	// 单文件
	f, err := c.FormFile("file")
	checkError(err)
	log.Println(f.Filename)

	src = gwd + src + f.Filename

	// 保存到指定路径
	err = c.SaveUploadedFile(f, src)
	checkError(err)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "upload successful",
	})

}

func main() {
	r := gin.Default()

	// gin表单限制上传大小默认为32MiB
	// 修改上传限制为1MiB
	r.MaxMultipartMemory = 1 << 20

	r.LoadHTMLGlob("templates/*")

	r.POST("/upload", UploadFile)
	r.GET("/upload", GetUploadPage)

	r.Run()
}

func checkError(e error) bool {
	if e != nil {
		log.Println(e)
		return false
	} else {
		return true
	}
}
